package com.blb.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * NIO的客户端
 */
public class NIOClient {

    private Selector selector;

    public void initClient(String ip,int port) throws IOException {
        //获得Socket通道
        SocketChannel channel = SocketChannel.open();
        //非阻塞
        channel.configureBlocking(false);
        //获得多路复用器
        selector = Selector.open();
        //连接服务器
        channel.connect(new InetSocketAddress(ip,port));
        //注册连接服务器的事件
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    public void connect() throws IOException {
        //轮询事件
        while(true){
            selector.select();
            //获得事件迭代器，遍历迭代器
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while(iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                //判断当前事件类型是连接
                if(key.isConnectable()){
                    SocketChannel sc = (SocketChannel) key.channel();
                    //完成连接
                    if(sc.isConnectionPending()){
                        sc.finishConnect();
                    }
                    sc.configureBlocking(false);
                    //给服务器发送消息
                    ByteBuffer byteBuffer = ByteBuffer.wrap("Hello服务器".getBytes());
                    sc.write(byteBuffer);
                    //注册读事件
                    sc.register(selector,SelectionKey.OP_READ);
                }else if(key.isReadable()){
                    //如果是读事件，就读取服务器消息
                    SocketChannel sc = (SocketChannel) key.channel();
                    //分配缓冲区，将数据读到缓冲区
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = sc.read(buffer);
                    if(len != -1){
                        String msg = new String(buffer.array(),0,len);
                        System.out.println("服务器说：" + msg);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClient("192.168.114.22",8888);
        client.connect();
    }
}
